package com.knight.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.knight.common.constant.Constant;
import com.knight.exception.RequestParameterException;
import com.knight.model.Menu;
import com.knight.model.Project;
import com.knight.service.MenuService;
import com.knight.service.ProjectsService;

/**
 * 工程案例
 * 
 * @author YQ
 *
 */
public class ProjectController extends Controller {
	private static MenuService menuService = MenuService.getInstance();
	private static ProjectsService projectsService = ProjectsService.getInstance();

	/**
	 * 项目详情
	 * 
	 * @throws RequestParameterException
	 * @throws Exception
	 */
	public void detail() throws Exception {
		List<Menu> list = menuService.findMenuByparentId(Constant.MenuTypes.LEVEL_TWO_MENU,
				Constant.ParentMenuId.PROJECTS_ID);
		setAttr("menus", list);
		String requestData = getPara();
		Map<String, String> map = commonMethod(list, requestData, this);
		String id = map.get("id");
		Project project = projectsService.findById(id);
		String urls = project.getUrls();
		List<String> urlList = new ArrayList<String>();
		if (urls.contains(Constant.Symbo.COMMA)) {
			urlList = Arrays.asList(urls.split(Constant.Symbo.COMMA));
		} else {
			urlList.add(urls);
		}
		setAttr("pname", project.get("name"));
		setAttr("urls", urlList);
		setAttr("parentId", project.getMenuId());
		render("anlijieshao.html");
	}

	/**
	 * 公共方法
	 * 
	 * @param list
	 * @param requestData
	 * @param controller
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> commonMethod(List<Menu> list, String requestData, Controller controller)
			throws Exception {
		if (list == null || list.size() == 0) {
			throw new RequestParameterException(Constant.ExceptionMessage.PARAMETER_IS_NULL);
		}
		Menu firstMenu = list.get(0);
		String id = null;
		if (requestData != null) {
			id = controller.getPara(0);
		} else {
			firstMenu.getParentId();
			id = firstMenu.get("id").toString();
		}
		controller.setAttr("menus", list);
		Menu m = menuService.findByPrimaryKey(firstMenu.getParentId());
		controller.setAttr("secondMenuName", m.getName());

		Map<String, String> map = new HashMap<String, String>();

		map.put("id", id);

		return map;
	}
}
